package com.arcsoft.arcfacedemo.service;

import android.app.Service;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;

import com.arcsoft.arcfacedemo.R;
import com.arcsoft.arcfacedemo.activity.RegisterAndRecognizeActivity;
import com.arcsoft.arcfacedemo.common.Constants;
import com.arcsoft.arcfacedemo.faceserver.FaceServer;
import com.arcsoft.face.ActiveFileInfo;
import com.arcsoft.face.ErrorInfo;
import com.arcsoft.face.FaceEngine;
import com.arcsoft.face.enums.RuntimeABI;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class ActiveService extends Service {
    private static final String TAG = "myservice";
    private LocalBinder mbinder = new LocalBinder();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    public class LocalBinder extends Binder {
        public ActiveService getservices(){
            return ActiveService.this;
        }
        public void start(){
            Log.e(TAG, "start:" );
        }
        public void end(){
            Log.e(TAG, "end:" );
        }
    }

    @Override
    public void onCreate() {
        Log.e(TAG, "onCreate:");
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand:");
        ActiveFileInfo activeFileInfo = new ActiveFileInfo();
        boolean initSuccess = FaceServer.getInstance().init(this);
        if(!initSuccess) {
            Log.d("激活状态","未激活");
            activeEngine(null);

        }else{
            Log.d("激活状态","已激活");
            Intent intent2 = new Intent("com.arcsoft.arcsoftdemo.faceactive");
            intent2.putExtra("isActive",true);
            sendBroadcast(intent2);
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "onDestroy:");
        super.onDestroy();
    }

    public  String myway(){
        Log.e(TAG, "myway:hello world");
        return "hello world";
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.e(TAG, "onUnbind:");
        return super.onUnbind(intent);
    }


    boolean libraryExists = true;
    // Demo 所需的动态库文件
    private static final String[] LIBRARIES = new String[]{
            // 人脸相关
            "libarcsoft_face_engine.so",
            "libarcsoft_face.so",
            // 图像库相关
            "libarcsoft_image_util.so",
    };

    private boolean checkSoFile(String[] libraries) {
        File dir = new File(getApplicationInfo().nativeLibraryDir);
        File[] files = dir.listFiles();
        if (files == null || files.length == 0) {
            return false;
        }
        List<String> libraryNameList = new ArrayList<>();
        for (File file : files) {
            libraryNameList.add(file.getName());
        }
        boolean exists = true;
        for (String library : libraries) {
            exists &= libraryNameList.contains(library);
        }
        return exists;
    }

    /**
     * 激活引擎
     *
     * @param view
     */
    public void activeEngine(final View view) {
        if (!libraryExists) {
            return;
        }
        if (view != null) {
            view.setClickable(false);
        }

        Log.d("人脸识别服务日志：","正在激活人脸识别！");
        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> emitter) {
                RuntimeABI runtimeABI = FaceEngine.getRuntimeABI();
                Log.i(TAG, "subscribe: getRuntimeABI() " + runtimeABI);

                long start = System.currentTimeMillis();
                int activeCode = FaceEngine.activeOnline(ActiveService.this, Constants.APP_ID, Constants.SDK_KEY);
                Log.i(TAG, "subscribe cost: " + (System.currentTimeMillis() - start));
                emitter.onNext(activeCode);
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Integer>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Integer activeCode) {
                        boolean isActive = false;
                        if (activeCode == ErrorInfo.MOK) {
                            Log.d("激活状态（activeServer）","已正确激活");
                            isActive = true;

                        } else if (activeCode == ErrorInfo.MERR_ASF_ALREADY_ACTIVATED) {
                            //activeTipDialog.setContent("已经激活！");
                            //showToast(getString(R.string.already_activated));
                            isActive = true;
                            Log.d("激活状态（activeServer）","已经激活");
                        } else {
                            isActive = false;
                            Log.d("激活状态（activeServer）","失败码："+activeCode);
                            //activeTipDialog.setContent("激活失败！错误码："+activeCode);
                            //showToast(getString(R.string.active_failed, activeCode));
                        }

                        Intent intent = new Intent("com.arcsoft.arcsoftdemo.faceactive");
                        intent.putExtra("isActive",isActive);
                        sendBroadcast(intent);

                    }

                    @Override
                    public void onError(Throwable e) {
                        if (view != null) {
                            view.setClickable(true);
                        }
                    }

                    @Override
                    public void onComplete() {
//                        activeTipDialog.hide();
                    }
                });

    }

}
